package my.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.chainsaw.Main;

public class Demo {

	private final static Pattern url_pattern = Pattern.compile(
		    "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?");
		 
	/**
	 * 自动为文本中的url生成链接
	 * @param txt
	 * @param only_oschina
	 * @return
	 */
	public static String autoMakeLink(String txt, boolean only_oschina) {
	    StringBuilder html = new StringBuilder();
	    int lastIdx = 0;
	    Matcher matchr = url_pattern.matcher(txt);
	    while (matchr.find()) {
	        String str = matchr.group();            
	        html.append(txt.substring(lastIdx, matchr.start()));
	        if(!only_oschina || StringUtils.containsIgnoreCase(str, "oschina.net"))
	            html.append("<a href='"+str+"'>"+str+"</a>");
	        else
	            html.append(str);
	        lastIdx = matchr.end();
	    }
	    html.append(txt.substring(lastIdx));
	    return html.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(autoMakeLink("下载地址：http://www.sjcx.org/p/tomcat" , false));
	}
}
